<?php
declare (strict_types = 0);
namespace app\controller;

use think\facade\View;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use app\Common;


class Refund{
    //常用数据表内容 及常用字典

    var $dept=[];
    var $sex=[1=>'男',2=>'女'];

    var $status=array(1=>'正常',2=>'关闭',3=>'已使用',4=>'过期');
    var $v_type = [];
    var $back = "<script>setTimeout(function(){history.back();},3000)</script>";

    public function __construct(){

        $list = Db::table("user")->select()->toArray();
        foreach($list as $k=>$v){
            $this->users[$v['id']]=$v;
        }

        $list = Db::table("dept")->select()->toArray();
        foreach($list as $k=>$v){
            $this->dept[$v['id']]=$v;
        }


    }

    //
    public function index(){
    }

    //红包设置
    public function config(){
        $uid = Session::get('logonid');
        if(empty($uid)) return header('location:/index.php/login');

        $all=Request::param(); 
        if(!empty($all['id'])){
            if(!(is_numeric($all['min_member']) 
                && is_numeric($all['max_member']) 
                && is_numeric($all['min']) 
                && is_numeric($all['max']) 
                && is_numeric($all['day_max']) 
                && is_numeric($all['hours'])
                && is_numeric($all['comm_invite'])
                && is_numeric($all['comm_invite2']))){
                return "<h2>设置错误,请检查各个项是否为数字值！</h2>".$this->back;

            }

            if($all['comm_invite']>600) return "<h2 style='color:red;'>C1,C2推广红包超过600最大额!</h2>".$this->back;
            if($all['comm_invite2']>300) return "<h2 style='color:red;'>D,E,F推广红包超过300最大额!</h2>".$this->back;
            Db::table('refund_config')->save($all);
        }

        $row = Db::table('refund_config')->find(1);

        View::assign(['data'=>$row]);
        return View::fetch();
    }
 
    //红包算法
    //fun:玩乐红包的最大值，有这个就是玩乐红包
    //min:最小值 max:最大值
    public function make_refund($min=1,$max=100){
        if(!is_numeric($min) || !is_numeric($max) || $max<=$min ) return 0;
        return mt_rand($min*100,$max*100)/100;
    }

    public function refund_test(){
        for($i=0;$i<=100;$i++){
            echo $this->make_refund(0.01,0.1)."<br/>";
        }
    }
 
    //领红包功能
    //1.检查红包开关
    //2.检查红包开放时间
    //3.检查客户是否已领本次红包
    //4.满足条件则产生一个红包,金额在设定值范围内。

    public function get_refund(){

        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'学员登录后才能领取红包哦！']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $me = $arr['customer']; //return json(['code'=>0,'msg'=>'红包活动未开放哦！']);
        //$me=Db::table('customer')->find(1075);

        $cfg = Db::table('refund_config')->find(1);
        $open = $cfg['status'];
        if($open!=1) return json(['code'=>0,'msg'=>'哦豁！本次红包活动结束了，下次不要错过了！']);

        $dt = date('Y-m-d H:i:s');

        $st = $cfg['start_time'];
        $et = $cfg['end_time'];
        //if($dt<$st ||$dt>$et) return json(['code'=>0,'msg'=>'哦豁，现在不是红包活动期间哦！']);

        $time = date("Y-m-d H:i:s");
        if($time<$st || $time>$et) {
            return json(['code'=>0,'msg'=>'现在不是抢红包的时间哦！']);
        }

        $hours =$cfg['hours'];
        $day_max=$cfg['day_max']; 

        //游客,摩托车类学员,毕业学员 只能领玩乐红包
        if($me['fee_time']<'1' || $me['fee_id']>2 || $me['status']==5){
            $min =$cfg['min'];
            $max =$cfg['max'];
        }else{
            $min =$cfg['min_member'];
            $max =$cfg['max_member'];
        }
        if(!is_numeric($min) || !is_numeric($max) || ($min+$max)<=0) {
            return json(['code'=>0,'msg'=>'哎呀！红包已经抢完了，下次活动再来吧！']);
        }

        $sql ="select id,money,create_time from acc_log where customer_id=? and create_time like ? and type=4 and status=2 and money<10 order by create_time desc";
        $list = Db::query($sql,[$me['id'],date('Y-m-d').'%']);

        if(count($list)>=$day_max){
            return json(['code'=>0,'msg'=>'你今天已领了'.count($list).'个红包了，别贪心哦！']);
        }

        if(count($list)){
            $time_diff = time()-strtotime($list[0]['create_time']);
            if($time_diff/3600<$hours){
                $time_diff = Common::time_format($hours*3600-$time_diff);
                return json(['code'=>0,'msg'=>'距离下一个红包还有【'.$time_diff.'】,请得回来哦！']);
            }
        }

        //产生一个红包： 1~5
        $money = $this->make_refund($min,$max);

        if(!$money){
          return json(['code'=>0,'msg'=>'哦豁，红包还没准备好哦！'.$money]);  
        }

        $acc_log=array(
            'type'=>4,
            'customer_id'=>$me['id'],
            'dept_id'=>$me['dept_id'],
            'money'=>$money,
            'memo'=>'活动红包',
            'payment'=>'balance',
            'creater'=>2,
            'create_time'=>date('Y-m-d H:i:s'),
            'status'=>2,
            'check_by'=>2,
            'check_time'=>date('Y-m-d H:i:s')

        );
        $res2= Db::table('acc_log')->insert($acc_log);
        Db::execute('update customer set money=money+? where id=?',[$money,$me['id']]);

        return json(['code'=>1,'msg'=>'恭喜恭喜！你抢到红包【'.$money.'元】，可在【账单】中查看！','data'=>$money]);

    }

    //优惠券管理
    public function voucher_list(){
        $uid=Session::get('logonid');

        $all =Request::param();

        if(!empty($all['name'])){
            if(empty($all['name']) || !is_numeric($all['money'])){
                return "设置错误!".$this->back;
            }
            if($_FILES['file']['size']>0){
                $files =Common::upload();
                
                if($files['code']){
                    $all['image']=$files['msg'];
                }else{
                    return ($files['msg']);
                }
            }
            
            if(empty($all['id'])) unset($all['id']);
            Db::table('voucher')->save($all);
        }
        $list =Db::table('voucher');

        if(empty($uid)) {
            $list->where('status',1);
        }

        $list = $list->select()->toArray();
        foreach ($list as &$row){
            $row['status_name'] = $this->status[$row['status']];
        }        
        View::assign(['data'=>$list]);
        return View::fetch('voucher_config');
    }

    //我的优惠券
    public function my_voucher(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'请先登录！']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }
        $me = $arr['customer'];

        $list=Db::table('voucher_mine')->where('customer_id',$me['id']); 

        //
        if(!empty($all['status'])){
            $list=$list->where('status',$all['status']);
        }
        //类型
        if(!empty($all['type'])){
            $list=$list->where('voucher_id',$all['type']);
        }

        //$list=$list->whereRaw(" stime<'".date('Y-m-d H:i:s')."' and etime>'".date('Y-m-d H:i:s')."'");

        $list = $list->select()->toArray(); 

        foreach($list as &$item){
            $item['status_name'] = $this->status[$item['status']];
            $voucher = Db::table('voucher')->find($item['voucher_id']);
            if(date('Y-m-d H:i:s')>$voucher['etime']){
                $item['status']='已过期';
            }

            $item['type_name'] = $voucher['name'];
            $item['order_money'] = $voucher['order_money'];
        }

        return json(['code'=>1,'data'=>$list]);
    }


    //优惠券领取
    public function voucher_get(){
        $all=Request::param();
        if(empty($all['token'])){
            return json(['code'=>0,'msg'=>'登录后才能领优惠券哦！']);
        }        
        $token = new Token();
        $arr = $token->check_token($all['token']);
        if(!$arr['code']){
            return json($arr['msg']);
        }

        $me = $arr['customer'];

        //$me=Db::table('customer')->find(1075);

        if(!empty($all["voucher_get"])){


            //领取优惠券
            $voucher_mine = Db::table('voucher_mine')->where('customer_id',$me['id'])->where('voucher_id',$all['id'])->select()->toArray();
            if(count($voucher_mine)){
                return json(['code'=>0,'msg'=>'你已领过这张券了！']);
            }

            $voucher=Db::table('voucher')->find($all['id']);

            if(date('Y-m-d H:i:s')>$voucher['etime']) return json(['code'=>0,'msg'=>'这张券过期了！']);
            if(date('Y-m-d H:i:s')<$voucher['stime']) return json(['code'=>0,'msg'=>'这张券领取时间还没到呢！']);

            $voucher =array(
                'voucher_id'=>$all['id'],
                'customer_id'=>$me['id'],
                'sn'=>'xjpa_'.Common::randomString(10),
                'status'=>1,
                'money'=>Db::table('voucher')->where('id',$all['id'])->value('money'),
                'create_time'=>date('Y-m-d H:i:s')
            );
            $res = Db::table('voucher_mine')->insert($voucher);
            if($res){
                return json(['code'=>1,'msg'=>'领到一张券！','sn'=>$voucher['sn']]);
            }
        }


        $list =Db::table('voucher')->where('status',1)->select()->toArray();

        foreach($list as &$voucher){
            $voucher['mine'] = Db::table('voucher_mine')->where('customer_id',$me['id'])->where('voucher_id',$voucher['id'])->select()->toArray();
        }

        return json(['code'=>1,'data'=>$list]);

    }
}
